<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 160px;"
        />
      </el-form-item>
      <el-form-item label="文章来源" prop="articleOrigin" v-if="canAudit">
        <el-input
          v-model="queryParams.articleOrigin"
          placeholder="请输入"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 160px;"
        />
      </el-form-item>
      <el-form-item label="栏目名称" prop="columnId">
        <el-select
          clearable
          filterable
          style="width: 160px;"
          v-model="queryParams.columnId" placeholder="请选择">
          <el-option
            placeholder="请选择"
            v-for="item in columnOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="责任编辑" prop="author" v-if="canAudit">
        <el-input
          v-model="queryParams.author"
          placeholder="请输入"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 160px;"
        />
      </el-form-item>
      <el-form-item label="审核状态" prop="state">
        <el-select v-model="queryParams.state" placeholder="请选择"
                   clearable
                   style="width: 160px;"
        >
          <el-option
            v-for="dict in dict.type.check"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="发布日期" prop="pubdate">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          clearable
        />
      </el-form-item>
      <el-form-item label="新闻正文" prop="content">
        <el-input
          v-model="queryParams.content"
          placeholder="请输入新闻正文"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 160px;"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['uncheck:uncheck:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['uncheck:uncheck:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDeleteData"
          v-hasPermi="['uncheck:uncheck:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['uncheck:uncheck:export']"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-document"
          size="mini"
          @click="handleOpenDraftBox"
        >草稿箱
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="uncheckList" @selection-change="handleSelectionChange" width="100%">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="id"  width="50"align="center" prop="articleId"/>
      <el-table-column label="标题" align="center" width="100" prop="title">
      <template slot-scope="scope">
        {{ $stripHtml(scope.row.title) }}
      </template>
      </el-table-column>
      <el-table-column label="文章来源" align="center" prop="articleOrigin"/>
      <el-table-column label="栏目名称" align="center" prop="columnName"/>
      <el-table-column label="内容" align="center" prop="content" width="250">
        <template slot-scope="scope">
          <div class="content-cell">{{ formatContent(scope.row.content) }}</div>
        </template>
      </el-table-column>
      <el-table-column label="责任编辑" align="center" prop="author"/>
      <el-table-column label="备注" align="center" prop="remark"/>
      <!-- <el-table-column label="封面路径" align="center" prop="coverPath" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.coverPath" :width="50" :height="50"/>
        </template>
      </el-table-column> -->
      <el-table-column label="审批表" align="center" prop="appval" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.appval" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="审核日期" align="center" prop="pubdate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.pubdate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="state">
        <template slot-scope="scope">
          <el-tag size="medium" :type="scope.row.state==0?'danger':scope.row.state==1?'success':'warning'">
            <dict-tag :options="dict.type.check" :value="scope.row.state"/>
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['uncheck:uncheck:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDeleteData(scope.row)"
            v-hasPermi="['uncheck:uncheck:remove']"
          >删除
          </el-button>
          <!-- 审核 -->
          <el-button
            v-if="canAudit"
            size="mini"
            type="text"
            @click="handleAudit(scope.row)"
          >审核
          </el-button>
          <!-- 驳回 -->
          <el-button
            v-if="canAudit"
            size="mini"
            type="text"
            @click="handleReject(scope.row)"
          >驳回
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="handlePagination"
    />

    <!-- 添加或修改uncheck对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <enhanced-editor v-model="form.title" :min-height="120" :max-height="200" placeholder="请输入内容"/>
        </el-form-item>
        <!-- 副标题部分 -->
        <el-form-item label="副标题">
          <div v-for="(subtitle, index) in subtitles" :key="index" class="subtitle-item">
            <enhanced-editor v-model="form[`littleTitle${index + 1}`]" :placeholder="`请输入副标题${index + 1}`"  :min-height="120" :max-height="200" />
          </div>
          <el-button
            v-if="subtitles.length < 2"
            type="text"
            icon="el-icon-plus"
            @click="addSubtitle"
          >
            添加副标题
          </el-button>
        </el-form-item>
        <el-form-item label="文章来源" prop="articleOrigin">
          <el-autocomplete
            v-model="form.articleOrigin"
            :fetch-suggestions="querySearchSource"
            placeholder="请输入文章来源"
            clearable
            style="width: 223px;"
          />
        </el-form-item>
        <el-form-item label="栏目名称" prop="columnId">
          <el-select
            clearable
            filterable
            v-model="form.columnId"
            placeholder="请选择"
            @change="handleColumnChange">
            <el-option
              placeholder="请选择"
              v-for="item in columnOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="责任编辑" prop="author">
          <el-autocomplete
            v-model="form.author"
            :fetch-suggestions="querySearchAuthor"
            placeholder="请输入责任编辑"
            clearable
            style="width: 223px;"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>

        <!-- 封面路径 - 只有媒体聚焦栏目才显示 -->
        <el-form-item label="封面路径" prop="coverPath" v-if="isMediaFocusColumn">
          <el-upload
            ref="upload"
            :file-list="fileList"
            :before-upload="beforeUpload"
            :on-change="handleFileChange"
            :auto-upload="false"
            :on-remove="handleRemove"
            :limit="1"
            list-type="picture-card"
            accept="image/*"
            action="#"
            :http-request="handleHttpRequest"
          >
            <i class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">请上传封面图片，大小不小于1MB</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="审批表" prop="appval">
          <el-upload
            ref="appvalUpload"
            :file-list="appvalFileList"
            :before-upload="beforeAppvalUpload"
            :on-change="handleAppvalFileChange"
            :auto-upload="false"
            :on-remove="handleAppvalRemove"
            :limit="1"
            list-type="picture-card"
            accept="image/*"
            action="#"
            :http-request="handleAppvalHttpRequest"
          >
            <i class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">请上传审批表图片</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="附件" prop="attachment">
          <el-upload
            ref="attachmentUpload"
            :file-list="attachmentFileList"
            :before-upload="beforeAttachmentUpload"
            :on-change="handleAttachmentFileChange"
            :auto-upload="false"
            :on-remove="handleAttachmentRemove"
            :limit="1"
            list-type="text"
            action="#"
            :http-request="handleAttachmentHttpRequest"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <el-button
              v-if="form.attachment || temporaryAttachmentUrl"
              size="small"
              type="success"
              icon="el-icon-download"
              @click.stop="downloadAttachment(form.attachment || temporaryAttachmentUrl, getAttachmentFileName(form.attachment || temporaryAttachmentUrl))"
              style="margin-left: 10px;"
            >
              下载附件
            </el-button>
            <div slot="tip" class="el-upload__tip">请上传附件文件</div>
          </el-upload>
        </el-form-item>

        <!-- 对分局隐藏 -->
        <el-form-item v-if="false" label="author对应的登录ip地址" prop="ip">
          <el-input v-model="form.ip" placeholder="请输入author对应的登录ip地址"/>
        </el-form-item>
        <el-form-item v-if="false" label="审核日期" prop="pubdate">
          <el-date-picker clearable
                          v-model="form.pubdate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择审核日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item v-if="false" label="0未审核1审核" prop="state">
          <el-select v-model="form.state" placeholder="请选择0未审核1审核">
            <el-option
              v-for="dict in dict.type.check"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <!-- 编辑草稿时显示更新草稿、直接发布、取消按钮 -->
        <template v-if="title === '修改草稿'">
          <el-button type="primary" @click="handleUpdateDraft" :loading="draftLoading">更新草稿</el-button>
          <el-button type="success" class="draft-publish-button" @click="handlePublishFromDraft" :loading="publishLoading">直接发布</el-button>
          <el-button @click="cancel">取消</el-button>
        </template>
        <!-- 编辑正式文章时显示确定、保存草稿、取消按钮 -->
        <template v-else>
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button type="warning" class="draft-save-button" @click="handleSaveDraft">保存草稿</el-button>
          <el-button @click="cancel">取 消</el-button>
        </template>
      </div>
    </el-dialog>


    <!-- 草稿箱弹窗 -->
    <el-dialog
      title="草稿箱"
      :visible.sync="draftBoxVisible"
      width="1200px"
      append-to-body
      custom-class="draft-dialog"
      top="5vh"
    >
      <el-table v-loading="draftLoading" :data="draftList" width="100%">
        <el-table-column label="标题" align="center" prop="title" >
          <template slot-scope="scope">
            {{ $stripHtml(scope.row.title) }}
          </template>
        </el-table-column>
        <el-table-column label="文章来源" align="center" prop="articleOrigin" />
        <el-table-column label="栏目名称" align="center" prop="columnName" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template slot-scope="scope">
            <span>{{ formatDateTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
          <template slot-scope="scope">
            <span>{{ formatDateTime(scope.row.updateTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="审批表" align="center" prop="appval" width="100">
          <template slot-scope="scope">
            <span :class="scope.row.appval && scope.row.appval !== '' ? 'has-approval' : 'no-approval'">
              {{ scope.row.appval && scope.row.appval !== '' ? '已上传' : '未上传' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleEditDraft(scope.row)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-check"
              @click="handlePublishDraft(scope.row)"
            >发布</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDeleteDraft(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="draftList.length>0"
        :total="draftList.length"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="loadDraftList"
      />
    </el-dialog>
  </div>
</template>

<script>
import {listUncheck, getUncheck, delUncheck, addUncheck, updateUncheck, listUncheckSeek} from "@/api/uncheck/uncheck";
import {listConlumn, getConlumn, listConlumnListByRole} from "@/api/conlumn/conlumn";
import {auditArticle, updateToArticle, delArticleByAuditId, uploadContentImage} from "../../../api/uncheck/uncheck";
import { uploadUncheckFile,uploadUncheckAppval,uploadUncheckAttachment,logicDeleteUncheck} from "@/api/uncheck/uncheck";
import {listUncheckDraft, getUncheckDraft, delUncheckDraft, publishUncheckDraft, addUncheckDraft, updateUncheckDraft} from "@/api/uncheck/draft";
import imageCompression from "browser-image-compression";
import EnhancedEditor from "@/components/Editor/EnhancedEditor";
import Vue from 'vue';

export default {
  name: "Uncheck",
  dicts: ['check'],
  components: {
    EnhancedEditor
  },
  data() {
    this.rootImagePath = 'https://web-ya-40.oss-cn-hangzhou.aliyuncs.com/river/filePath'
    return {

      sourceHistory: [], // 存储文章来源的历史记录（市局输入记忆功能）- 使用固定大小为10的循环缓冲区
      authorHistory: [], // 存储责任编辑的历史记录 - 使用固定大小为10的循环缓冲区

      isSeekMode: false, // 新增字段，用于标识是否处于参数查询模式
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // uncheck表格数据
      uncheckList: [],
      //栏目名称列表数据
      columnOptions: [],
      canAdd: false,
      canAudit: false,
      userName: null,
      isAdmin: false,
      // 草稿箱相关
      draftBoxVisible: false,
      draftList: [],
      draftLoading: false,
      publishLoading: false, // 发布加载状态
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        articleOrigin: null,
        columnId: null,
        author: null,
        state: null,
        content: null
      },
      // 日期区间参数
      dateRange: [],
    };
  },
  computed: {
  },
  watch: {
    // 监听路由参数变化
    '$route.query': {
      handler(newQuery, oldQuery) {
        // 当路由参数变化时，重新初始化页面
        if (newQuery.operationType !== oldQuery.operationType || newQuery.id !== oldQuery.id) {
          this.initPage();
        }
      },
      deep: true,
      immediate: false
    }
  },
  created() {
    this.getList();
    this.getColumnList();
    this.getList();

    // 加载文章来源历史记录
    const storedHistory = localStorage.getItem('sourceHistory');
    if (storedHistory) {
      const historyData = JSON.parse(storedHistory);
      // 过滤掉超过3天的数据
      const thirtyDaysAgo = Date.now() - (3 * 24 * 60 * 60 * 1000);
      this.sourceHistory = historyData.filter(item => item.timestamp > thirtyDaysAgo)
        .map(item => item.value);
    }

    // 加载责任编辑历史记录
    const storedAuthorHistory = localStorage.getItem('authorHistory');
    if (storedAuthorHistory) {
      const authorHistoryData = JSON.parse(storedAuthorHistory);
      // 过滤掉超过3天的数据
      const thirtyDaysAgo = Date.now() - (3 * 24 * 60 * 60 * 1000);
      this.authorHistory = authorHistoryData.filter(item => item.timestamp > thirtyDaysAgo)
        .map(item => item.value);
    }
  },

  methods: {


    // 验证封面是否满足要求
    validateCover() {
      // 草稿箱中的文章不需要强制验证封面
      // 无论是新建还是修改草稿，都不强制要求上传封面
      // 但发布草稿时仍需要验证封面
      try {
        const stack = new Error().stack;
        if (stack && (stack.includes('handleSaveDraft') || stack.includes('handleUpdateDraft'))) {
          // 如果是从保存草稿或更新草稿方法调用的，跳过封面验证
          return true;
        }
        // 如果是从handlePublishFromDraft调用的，不应该跳过验证，应该继续执行下面的验证逻辑
      } catch (e) {
        // 如果无法获取调用栈，继续正常验证流程
        console.log('无法获取调用栈信息');
      }

      // 检查是否是媒体聚焦栏目
      if (this.isMediaFocusColumn) {
        // 检查是否有封面图片：form.coverPath、uploadFile 或 fileList 中有文件
        const hasCoverImage = this.form.coverPath ||
                             this.uploadFile ||
                             (this.fileList && this.fileList.length > 0);

        console.log('封面验证调试信息:', {
          isMediaFocusColumn: this.isMediaFocusColumn,
          formCoverPath: this.form.coverPath,
          uploadFile: this.uploadFile,
          fileList: this.fileList,
          hasCoverImage: hasCoverImage
        });

        if (!hasCoverImage) {
          this.$modal.msgError("媒体聚焦栏目必须上传封面图片");
          return false;
        }
      }
      return true;
    },

    // 清空封面相关数据
    clearCoverData() {
      this.form.coverPath = null;
      this.uploadFile = null;
      this.fileList = [];
      // 清空上传组件的文件列表
      if (this.$refs.upload) {
        this.$refs.upload.clearFiles();
      }
    },

    /** 处理栏目变化 */
    handleColumnChange(value) {
      // 当栏目变化时，检查是否需要清空封面
      // 如果之前选择了媒体聚焦栏目，现在切换到其他栏目，或者从其他栏目切换到媒体聚焦栏目
      // 都需要清空之前的封面状态

      // 清空封面相关数据
      this.clearCoverData();

      // 更新表单中的栏目名称
      if (value) {
        const selectedColumn = this.columnOptions.find(col => col.id === value);
        if (selectedColumn) {
          this.form.name = selectedColumn.name;
        }
      } else {
        this.form.name = '';
      }
    },

    querySearchAuthor(queryString, cb) {
      // 从 localStorage 获取最新数据
      let storedHistory = [];
      const storedHistoryStr = localStorage.getItem('authorHistory');
      if (storedHistoryStr) {
        try {
          storedHistory = JSON.parse(storedHistoryStr);
        } catch (e) {
          console.error('解析历史记录失败:', e);
          storedHistory = [];
        }
      }

      // 过滤掉超过3天的数据
      const thirtyDaysAgo = Date.now() - (3 * 24 * 60 * 60 * 1000);
      storedHistory = storedHistory.filter(item => item.timestamp > thirtyDaysAgo);

      // 提取值并过滤
      const historyValues = storedHistory.map(item => item.value);
      const results = queryString
        ? historyValues.filter(item => item.includes(queryString))
        : historyValues;

      cb(results.map(item => ({ value: item })));
    },

    addToAuthorHistory(author) {
      if (!author) return;

      // 从 localStorage 获取现有数据
      let storedHistory = [];
      const storedHistoryStr = localStorage.getItem('authorHistory');
      if (storedHistoryStr) {
        try {
          storedHistory = JSON.parse(storedHistoryStr);
        } catch (e) {
          console.error('解析历史记录失败:', e);
          storedHistory = [];
        }
      }

      // 检查是否已存在
      const existingIndex = storedHistory.findIndex(item => item.value === author);
      if (existingIndex !== -1) {
        // 如果已存在，将其移到数组开头
        const existingItem = storedHistory.splice(existingIndex, 1)[0];
        storedHistory.unshift(existingItem);
      } else {
        // 如果不存在，添加到数组开头
        storedHistory.unshift({ value: author, timestamp: Date.now() });

        // 如果数组长度超过10，移除最后一个元素
        if (storedHistory.length > 10) {
          storedHistory.pop();
        }
      }

      // 更新 localStorage
      localStorage.setItem('authorHistory', JSON.stringify(storedHistory));

      // 更新当前组件的 authorHistory（只保存值）
      this.authorHistory = storedHistory.map(item => item.value);
    },


    querySearchSource(queryString, cb) {
      // 从 localStorage 获取最新数据
      let storedHistory = [];
      const storedHistoryStr = localStorage.getItem('sourceHistory');
      if (storedHistoryStr) {
        try {
          storedHistory = JSON.parse(storedHistoryStr);
        } catch (e) {
          console.error('解析历史记录失败:', e);
          storedHistory = [];
        }
      }

      // 过滤掉超过3天的数据
      const thirtyDaysAgo = Date.now() - (3 * 24 * 60 * 60 * 1000);
      storedHistory = storedHistory.filter(item => item.timestamp > thirtyDaysAgo);

      // 提取值并过滤
      const historyValues = storedHistory.map(item => item.value);
      const results = queryString
        ? historyValues.filter(item => item.includes(queryString))
        : historyValues;

      cb(results.map(item => ({ value: item })));
    },

    addSubtitle() {
      if (this.subtitles.length < 2) {
        this.subtitles.push(`littleTitle${this.subtitles.length + 1}`);
      }
    },

    handleDeleteData(row){
      const articleIds = row.articleId || this.ids;
      this.$modal.confirm('是否确认删除编号为"' + articleIds + '"的数据项?').then(function (){
        return logicDeleteUncheck(articleIds);
      }).then(()=>{
        delUncheck(articleIds);
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(()=>{
        // 删除失败时不向用户显示错误提示，只记录日志
        console.warn("删除数据失败，但不向用户显示错误提示");
      });

    },
    //Canvas 进行图片压缩
    async compressImage(file, checkMinSize = true) {
      const minSizeBytes = 1024 * 1024; // 1MB 下限
      const maxSizeBytes = 5 * 1024 * 1024; // 5MB 上限
      const skipCompressSizeBytes = 3 * 1024 * 1024; // 3MB

      // 检查文件是否小于最小大小（仅当checkMinSize为true时检查）
      if (checkMinSize && file.size < minSizeBytes) {
        throw new Error('图片大小不能小于1MB!');
      }

      // 如果文件小于 3MB，直接跳过压缩
      if (file.size < skipCompressSizeBytes) {
        console.log(`文件大小为 ${file.size} bytes，小于 3MB，跳过压缩`);
        return file;
      }

      // 所有图片都使用 Canvas 进行精确压缩，确保不会低于下限
      return await this.canvasCompress(file, minSizeBytes, maxSizeBytes);
    },

    //Canvas 进行精确压缩
    async canvasCompress(file, minSizeBytes, maxSizeBytes) {
      return new Promise((resolve, reject) => {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        const img = new Image();

        img.onload = async () => {
          // 初始宽高
          let width = img.width;
          let height = img.height;

          // 计算缩放比例
          const ratio = width / height;

          // 如果图片很大，先进行初步缩放
          if (width > 2048 || height > 2048) {
            if (width > height) {
              width = 2048;
              height = 2048 / ratio;
            } else {
              height = 2048;
              width = 2048 * ratio;
            }
          }

          // 设置 canvas 尺寸
          canvas.width = width;
          canvas.height = height;

          // 绘制图片到 canvas
          ctx.drawImage(img, 0, 0, width, height);

          // 二分法查找合适的质量参数
          let quality = 1;
          let minQuality = 0.1;
          let maxQuality = 2;
          let attempts = 0;
          const maxAttempts = 10;

          let compressedBlob;

          while (attempts < maxAttempts) {
            attempts++;

            // 导出为 Blob
            compressedBlob = await new Promise(resolve => {
              canvas.toBlob(resolve, 'image/jpeg', quality);
            });

            console.log(`第 ${attempts} 次压缩尝试，质量: ${quality}, 大小: ${compressedBlob.size} bytes`);

            // 检查大小是否符合要求
            if (compressedBlob.size >= minSizeBytes && compressedBlob.size <= maxSizeBytes) {
              console.log('压缩成功，大小符合要求');
              break;
            }

            // 调整质量参数
            if (compressedBlob.size > maxSizeBytes) {
              // 太大了，降低质量
              maxQuality = quality;
              quality = (minQuality + quality) / 2;
            } else {
              // 太小了，提高质量
              minQuality = quality;
              quality = (quality + maxQuality) / 2;
            }

            // 如果质量调整过小，可能无法达到最小大小要求
            if (quality < 0.01) {
              console.warn('质量参数过低，无法达到最小大小要求');
              break;
            }
          }

          // 如果最终结果还是太小，使用最小质量重新压缩
          if (compressedBlob.size < minSizeBytes) {
            console.warn(`压缩后文件过小 (${compressedBlob.size} bytes)，使用最小质量重新压缩`);
            compressedBlob = await new Promise(resolve => {
              canvas.toBlob(resolve, 'image/jpeg', 0.95);
            });
          }

          // 转换为 File 对象
          const compressedFile = new File([compressedBlob], file.name, {
            type: 'image/jpeg',
            lastModified: Date.now()
          });

          console.log(`最终压缩结果: ${compressedFile.size} bytes`);
          resolve(compressedFile);
        };

        img.onerror = () => {
          reject(new Error('图片加载失败'));
        };

        // 读取文件
        const reader = new FileReader();
        reader.onload = e => {
          img.src = e.target.result;
        };
        reader.onerror = () => {
          reject(new Error('文件读取失败'));
        };
        reader.readAsDataURL(file);
      });
    },

    // 审批表上传请求处理
    handleAppvalHttpRequest(options) {
      this.uploadAppvalToServer(options.file);
    },

    // 附件上传请求处理
    async handleAttachmentHttpRequest(options) {
      try {
        const response = await this.uploadAttachmentToServer(options.file);
        if (response && response.code === 200 && response.url) {
          // 设置文件的URL，使Element UI上传组件能够显示可点击的文件链接
          const fileData = {
            name: options.file.name,
            url: response.url
          };
          options.onSuccess(fileData);
        } else {
          options.onError(new Error(response.msg || '上传失败'));
        }
      } catch (error) {
        options.onError(error);
      }
    },

    // 上传审批表文件到服务器
    async uploadAppvalToServer(file) {
       // 确保传入的是有效的文件对象
      if (!file || !(file instanceof File)) {
        console.error('无效的文件对象:', file);
        this.$message.error('审批表文件无效');
        return;
      }

      try {
        // 压缩图片
        //console.log('提交前压缩审批表');
        //const compressedFile = await this.compressImage(file);

        const formData = new FormData();
        formData.append('appvalPath', file);

        console.log('调用审批表上传API，ID:', this.form.articleId || 0);
        const response = await uploadUncheckAppval(this.form.articleId || 0, formData);
        console.log('审批表上传响应:', response);
        if (response.code === 200) {
          this.form.appval = response.url;
          // 更新审批表状态
          this.appvalState.currentUrl = response.url;
          this.appvalState.pendingFile = null;
          this.appvalState.isRemoved = false;
          this.$message.success('审批表上传成功');
          return response;
        } else {
          throw new Error(response.msg || '上传失败');
        }
      } catch (error) {
        console.error('审批表上传失败:', error);
        this.$message.error('审批表上传失败: ' + error.message);
        throw error;
      }
    },

    // 上传附件文件到服务器
    async uploadAttachmentToServer(file) {
      // 确保传入的是有效的文件对象
      if (!file || !(file instanceof File)) {
        console.error('无效的文件对象:', file);
        this.$message.error('附件文件无效');
        return;
      }

      const formData = new FormData();
      formData.append('file', file);

      try {
        const response = await uploadUncheckAttachment(this.form.articleId || 0, formData);
        if (response.code === 200) {
          this.form.attachment = response.url;
          this.$message.success('附件上传成功');
          return response;
        } else {
          throw new Error(response.msg || '上传失败');
        }
      } catch (error) {
        console.error('附件上传失败:', error);
        this.$message.error('附件上传失败: ' + error.message);
        throw error;
      }
    },


    handleHttpRequest(options) {
      console.log('封面上传请求处理:', options);
      this.uploadFileToServer(options.file);
    },

    // 修改后的上传方法
    async uploadFileToServer(file) {
      try {
        // 检查是否为虚拟File对象（带有url属性的OSS图片）
        if (file.url) {
          // 对于OSS图片，直接使用URL
          this.form.coverPath = file.url;
          this.$message.success('封面图片设置成功');
          return { code: 200, url: file.url };
        } else {
          // 对于草稿，可以适当压缩以节省存储空间
          let fileToUpload = file;
          if (this.title === "修改草稿" || this.title === "添加文章") {
            console.log('对草稿封面图片进行压缩处理');
            try {
              // 对于草稿，使用更宽松的压缩参数
              fileToUpload = await this.compressImage(file, false); // 不检查最小大小限制
            } catch (compressError) {
              console.warn('封面图片压缩失败，使用原文件:', compressError.message);
              // 压缩失败时使用原文件
              fileToUpload = file;
            }
          } else {
            // 对于媒体聚焦栏目，需要检查最小1MB限制
            if (this.isMediaFocusColumn) {
              console.log('对媒体聚焦栏目封面图片进行压缩处理，检查最小1MB限制');
              try {
                fileToUpload = await this.compressImage(file, true); // 检查最小大小限制
              } catch (compressError) {
                console.error('封面图片压缩失败:', compressError);
                // 显示提醒并中断上传流程
                //this.$message.warning('封面大小不能小于1MB!');
                throw new Error('封面大小不能小于1MB!'); // 抛出错误以中断上传流程
              }
            } else {
              console.log('直接上传封面图片，不进行压缩');
            }
          }

          const formData = new FormData();
          formData.append('file', fileToUpload);

          console.log('调用封面上传API，ID:', this.form.articleId || 0);
          const response = await uploadUncheckFile(this.form.articleId || 0, formData);

          console.log('封面上传响应:', response);
          if (response.code === 200) {
            this.form.coverPath = response.url;
            this.$message.success('封面图片上传成功');
            return response;
          } else {
            throw new Error(response.msg || '上传失败');
          }
        }
      } catch (error) {
        console.error('上传失败:', error);
        this.$message.error('封面图片上传失败: ' + error.message);
        throw error;
      }
    },

    // 封面上传前处理
    beforeUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt1M = file.size / 1024 / 1024 < 1; // 检查是否小于1MB

      if (!isImage) {
        this.$message.error('只能上传图片文件!');
        return false;
      }
      if (isLt1M) {
        this.$message.warning('封面大小不能小于1MB!');
        // 不阻止上传，只显示提醒
      }

      this.uploadFile = file;
      return false; // 阻止自动上传
    },

    // 文件变化处理
    handleFileChange(file, fileList) {
      console.log('封面文件变化处理:', file, fileList);
      if (fileList.length > 0) {
        this.uploadFile = fileList[0].raw;
        this.fileList = [fileList[fileList.length - 1]]; // 只保留最后一个文件
        console.log('更新 uploadFile:', this.uploadFile);
      } else {
        this.uploadFile = null;
        this.fileList = [];
        this.form.coverPath = null;
        console.log('清空 uploadFile 和 coverPath');
      }
    },

    // 文件移除处理
    handleRemove() {
      console.log('封面文件移除处理');
      this.uploadFile = null;
      this.form.coverPath = null;
      this.fileList = [];
      console.log('清空 uploadFile 和 coverPath');
    },

    // 审批表上传前处理
    beforeAppvalUpload(file) {
      const isImage = file.type.startsWith('image/');

      if (!isImage) {
        this.$message.error('只能上传图片文件!');
        return false;
      }

      this.uploadAppvalFile = file;
      return false; // 阻止自动上传
    },

    // 审批表文件变化处理
    handleAppvalFileChange(file, fileList) {
      console.log('审批表文件变化处理:', file, fileList);
      if (fileList.length > 0) {
        this.uploadAppvalFile = fileList[fileList.length - 1].raw;
        this.appvalFileList = [fileList[fileList.length - 1]]; // 只保留最后一个文件
        console.log('更新 uploadAppvalFile:', this.uploadAppvalFile);

        // 更新审批表状态
        this.appvalState.pendingFile = fileList[fileList.length - 1].raw;
        this.appvalState.isRemoved = false;
        // 当有新文件选择时，不立即清除currentUrl，而是在上传成功后再更新
        // this.appvalState.currentUrl = null;  // 注释掉这一行
      } else {
        this.uploadAppvalFile = null;
        this.appvalFileList = [];
        // 标记为已移除并清空form.appval
        this.appvalState.isRemoved = true;
        this.form.appval = null; // 清空表单中的审批表URL
        this.appvalState.pendingFile = null;
        console.log('标记审批表为已移除');
      }
    },

    // 审批表文件移除处理
    handleAppvalRemove() {
      console.log('审批表文件移除处理');
      console.log('移除前状态:', {
        uploadAppvalFile: this.uploadAppvalFile,
        isRemoved: this.appvalState.isRemoved,
        currentUrl: this.appvalState.currentUrl,
        originalUrl: this.appvalState.originalUrl,
        formAppval: this.form.appval
      });
      this.uploadAppvalFile = null;
      // 标记为已移除并清空form.appval
      this.appvalState.isRemoved = true;
      this.form.appval = null; // 清空表单中的审批表URL
      this.appvalFileList = [];
      console.log('标记审批表为已移除');
      console.log('移除后状态:', {
        isRemoved: this.appvalState.isRemoved,
        currentUrl: this.appvalState.currentUrl,
        originalUrl: this.appvalState.originalUrl,
        formAppval: this.form.appval
      });
    },

    // 附件文件上传前处理
    beforeAttachmentUpload(file) {
      this.uploadAttachmentFile = file;
      console.log('设置 uploadAttachmentFile:', this.uploadAttachmentFile);
      return false; // 阻止自动上传
    },

    // 附件文件变化处理
    async handleAttachmentFileChange(file, fileList) {
      console.log('附件文件变化处理:', file, fileList);
      if (fileList.length > 0) {
        this.uploadAttachmentFile = fileList[0].raw;
        this.attachmentFileList = [fileList[fileList.length - 1]]; // 只保留最后一个文件
        console.log('设置 uploadAttachmentFile:', this.uploadAttachmentFile);

        // 立即上传附件文件，但不保存到数据库
        if (this.uploadAttachmentFile && this.uploadAttachmentFile instanceof File) {
          try {
            const response = await this.uploadAttachmentToServer(this.uploadAttachmentFile);
            if (response && response.code === 200 && response.url) {
              // 保存上传后的URL，但不立即更新到form.attachment
              this.temporaryAttachmentUrl = response.url;
              // 更新文件列表显示
              this.attachmentFileList = [{
                name: this.uploadAttachmentFile.name,
                url: response.url
              }];
              this.$message.success('附件上传成功，可点击下载预览');
            }
          } catch (error) {
            console.error('附件上传失败:', error);
            this.$message.error('附件上传失败: ' + error.message);
          }
        }
      } else {
        this.uploadAttachmentFile = null;
        this.attachmentFileList = [];
        this.temporaryAttachmentUrl = null; // 清空临时URL
        console.log('清空 uploadAttachmentFile');
      }
    },

    // 附件文件移除处理
    handleAttachmentRemove(file, fileList) {
      console.log('附件文件移除处理:', file, fileList);
      this.uploadAttachmentFile = null;
      this.form.attachment = null; // 清空表单中的附件URL
      this.temporaryAttachmentUrl = null; // 清空临时附件URL
      this.attachmentFileList = fileList || [];
      console.log('清空 uploadAttachmentFile 和 attachment');
    },

    // 获取附件文件名
    getAttachmentFileName(url) {
      if (!url) return '';
      const fileName = url.substring(url.lastIndexOf('/') + 1);
      // 移除查询参数
      return fileName.split('?')[0];
    },

    // 下载附件
    downloadAttachment(url, fileName) {
      if (!url) {
        this.$message.warning('附件链接无效');
        return;
      }

      // 创建隐藏的下载链接
      const link = document.createElement('a');
      link.href = url;
      link.download = fileName || this.getAttachmentFileName(url);
      link.style.display = 'none';

      // 添加到文档中并触发点击
      document.body.appendChild(link);
      link.click();

      // 清理
      document.body.removeChild(link);
    },


    /** 处理审批表上传 */
    async handleAppvalUpload() {
      try {
        // 检查是否有新的审批表文件需要上传
        if (this.uploadAppvalFile && this.uploadAppvalFile instanceof File) {
          console.log('处理审批表上传');
          console.log('提交前压缩审批表');
          this.uploadAppvalFile = await this.compressImage(this.uploadAppvalFile, false);
          const response = await this.uploadAppvalToServer(this.uploadAppvalFile);

          // 更新审批表状态
          if (response && response.url) {
            this.appvalState.currentUrl = response.url;
            this.appvalState.pendingFile = null;
            this.appvalState.isRemoved = false;
            this.appvalState.originalUrl = response.url; // 同步originalUrl
            this.form.appval = response.url; // 确保form.appval也被更新

            // 独立验证审批表上传结果
            console.log('审批表上传成功，验证状态同步:', {
              currentUrl: this.appvalState.currentUrl,
              originalUrl: this.appvalState.originalUrl,
              formAppval: this.form.appval
            });

            // 额外验证状态同步
            if (this.appvalState.currentUrl !== response.url || this.form.appval !== response.url) {
              console.warn('审批表状态同步可能存在延迟，强制同步状态');
              this.appvalState.currentUrl = response.url;
              this.appvalState.originalUrl = response.url;
              this.form.appval = response.url;
            }
          }

          console.log('审批表上传完成，更新状态:', {
            currentUrl: this.appvalState.currentUrl,
            originalUrl: this.appvalState.originalUrl,
            isRemoved: this.appvalState.isRemoved,
            formAppval: this.form.appval
          });

          return true;
        }
        // 检查用户是否移除了审批表
        else if (this.appvalState.isRemoved) {
          console.log('用户移除了审批表，清空appval字段');
          this.form.appval = null;
          this.appvalState.currentUrl = null;
          this.appvalState.originalUrl = null;
          return true;
        }
        // 如果没有变化，跳过上传
        else {
          console.log('跳过审批表上传 - 无变化');
          console.log('当前审批表状态:', {
            currentUrl: this.appvalState.currentUrl,
            originalUrl: this.appvalState.originalUrl,
            isRemoved: this.appvalState.isRemoved,
            formAppval: this.form.appval
          });
          return true;
        }
      } catch (error) {
        console.error('审批表上传失败:', error);
        this.$message.error('审批表上传失败: ' + error.message);
        throw error;
      }
    },

    /** 检查是否需要上传审批表 */
    needUploadAppval() {
      console.log('检查是否需要上传审批表:', {
        uploadAppvalFile: this.uploadAppvalFile,
        isFile: this.uploadAppvalFile instanceof File,
        isRemoved: this.appvalState.isRemoved,
        originalUrl: this.appvalState.originalUrl,
        currentUrl: this.appvalState.currentUrl,
        formAppval: this.form.appval
      });

      // 检查是否有新的审批表文件待上传
      if (this.uploadAppvalFile && this.uploadAppvalFile instanceof File) {
        console.log('需要上传：有新的审批表文件待上传');
        return true;
      }

      // 检查用户是否移除了审批表
      if (this.appvalState.isRemoved && this.appvalState.originalUrl) {
        console.log('需要上传：用户移除了审批表');
        return true;
      }

      // 检查URL是否发生变化
      if (this.appvalState.currentUrl !== this.appvalState.originalUrl) {
        console.log('需要上传：URL发生变化');
        console.log('currentUrl:', this.appvalState.currentUrl, 'originalUrl:', this.appvalState.originalUrl);
        return true;
      }

      // 检查表单中的appval字段是否与当前URL不一致
      if (this.form.appval && this.form.appval !== this.appvalState.currentUrl) {
        console.log('需要上传：表单appval与当前URL不一致');
        console.log('form.appval:', this.form.appval, 'currentUrl:', this.appvalState.currentUrl);
        return true;
      }

      console.log('不需要上传审批表');
      return false;
    },

    /** 检查审批表是否有效 */
    isValidAppval() {
      console.log('检查审批表是否有效:', {
        formAppval: this.form.appval,
        currentUrl: this.appvalState.currentUrl,
        uploadAppvalFile: this.uploadAppvalFile,
        isFile: this.uploadAppvalFile instanceof File,
        originalUrl: this.appvalState.originalUrl,
        isRemoved: this.appvalState.isRemoved
      });

      // 如果用户明确移除了审批表，则无效
      if (this.appvalState.isRemoved) {
        console.log('审批表无效：用户已移除审批表');
        return false;
      }

      // 检查表单中的appval字段
      if (this.form.appval && this.form.appval !== "") {
        console.log('审批表有效：表单中有appval字段');
        return true;
      }

      // 检查当前审批表URL
      if (this.appvalState.currentUrl && this.appvalState.currentUrl !== "") {
        console.log('审批表有效：当前有审批表URL');
        // 同步form.appval与currentUrl
        this.form.appval = this.appvalState.currentUrl;
        return true;
      }

      // 检查原始审批表URL
      if (this.appvalState.originalUrl && this.appvalState.originalUrl !== "") {
        console.log('审批表有效：有原始审批表URL');
        // 同步form.appval与originalUrl
        this.form.appval = this.appvalState.originalUrl;
        return true;
      }

      // 检查是否有待上传的审批表文件
      if (this.uploadAppvalFile && this.uploadAppvalFile instanceof File) {
        console.log('审批表有效：有待上传的审批表文件');
        return true;
      }

      // 特殊情况处理：如果form.appval为空但originalUrl不为空，说明审批表已存在
      if (!this.form.appval && this.appvalState.originalUrl) {
        console.log('审批表有效：使用原始审批表URL');
        // 同步form.appval与originalUrl
        this.form.appval = this.appvalState.originalUrl;
        return true;
      }

      console.log('审批表无效');
      return false;
    },

    formatContent(content) {
      // 先移除HTML标签
      const plainText = content.replace(/<[^>]*>/g, '');
      // 截取前100个字符（可根据需要调整）
      return plainText.length > 50 ? plainText.substring(0, 50) + '...' : plainText;
    },



    /** 专门处理审批表上传和验证的独立流程 */
    async handleAppvalUploadAndValidate() {
      try {
        console.log('开始独立审批表上传和验证流程');

        // 检查是否有新的审批表文件需要上传
        if (this.uploadAppvalFile && this.uploadAppvalFile instanceof File) {
          console.log('检测到新的审批表文件，开始处理');
          console.log('提交前压缩审批表');
          this.uploadAppvalFile = await this.compressImage(this.uploadAppvalFile, false);

          // 上传审批表
          const response = await this.uploadAppvalToServer(this.uploadAppvalFile);

          // 更新审批表状态
          if (response && response.url) {
            console.log('审批表上传成功:', response.url);
            this.appvalState.currentUrl = response.url;
            this.appvalState.pendingFile = null;
            this.appvalState.isRemoved = false;
            this.appvalState.originalUrl = response.url;
            this.form.appval = response.url;

            // 强制同步状态
            this.$forceUpdate();
            await this.$nextTick();

            console.log('审批表状态已更新:', {
              currentUrl: this.appvalState.currentUrl,
              originalUrl: this.appvalState.originalUrl,
              formAppval: this.form.appval
            });
          }
        }
        // 检查用户是否移除了审批表
        else if (this.appvalState.isRemoved) {
          console.log('用户移除了审批表');
          this.form.appval = null;
          this.appvalState.currentUrl = null;
          this.appvalState.originalUrl = null;
        }
        // 如果已有审批表，确保状态同步
        else if (this.appvalState.originalUrl && !this.form.appval) {
          console.log('同步已有审批表状态');
          this.form.appval = this.appvalState.originalUrl;
        }

        // 验证审批表是否有效
        const isValid = this.isValidAppval();
        console.log('审批表验证结果:', isValid);

        if (!isValid) {
          console.log('审批表无效，详细状态:', {
            formAppval: this.form.appval,
            currentUrl: this.appvalState.currentUrl,
            originalUrl: this.appvalState.originalUrl,
            isRemoved: this.appvalState.isRemoved
          });
        }

        return isValid;
      } catch (error) {
        console.error('独立审批表上传和验证流程失败:', error);
        return false;
      }
    },

    // 分页触发
    handlePagination() {
      if (this.isSeekMode) {
        this.getListSeek();
      } else {
        this.getList();
      }
    },
    /**
     * 驳回
     */
    handleReject(row) {
      // 弹出输入框，让用户填写驳回理由
      this.$prompt('请输入驳回理由', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /.+/, // 输入内容不能为空
        inputErrorMessage: '驳回理由不能为空'
      }).then(async ({value}) => {
        try {
          // 获取当前行的数据
          const response = await getUncheck(row.articleId);
          this.form = response.data;

          // 更新备注为用户输入的驳回理由
          this.form.remark = value;
          this.form.state = "2";

          // 提交更新
          await updateUncheck(this.form);
          this.getList();
        } catch (error) {
          this.$modal.msgError("操作失败，请重试");
          console.error(error);
        }
      }).catch(() => {
        // 用户点击取消时不做任何操作
        this.$message.info("已取消驳回");
      });
    },

    /**
     * 审核
     */
    handleAudit(row) {
      this.$router.push({
        path: '/uncheck/uncheck-audit/index',
        query: {
          id: row.articleId
        }
      });
    },

    formatDate(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    },

    /** 查询栏目列表 */
    getColumnList() {
      listConlumnListByRole().then(response => {
        this.columnOptions = response.rows;
      });
    },
    /** 查询uncheck列表 权限*/
    getList() {
      this.loading = true;
      listUncheck(this.queryParams).then(response => {
        const {rows, total} = response.data; // 从 response.data 中提取 rows 和 total
        this.canAdd = response.canAdd;         //设置 canAdd 权限字段
        this.canAudit = response.canAudit;
        this.userName = response.userName;
        this.isAdmin = response.isAdmin;

        if(!this.canAdd)
          this.dept = null;
        else
          this.dept = response.dept;

        // 直接使用后端返回的数据，后端已经进行了权限过滤
        this.uncheckList = rows.map(item => {
          const column = this.columnOptions.find(col => col.id === item.columnId);
          return {
            ...item,
            columnName: column ? column.name : '未知栏目'
          }
        });

        this.total = total;
        this.loading = false;
      });
    },

    /**
     * 条件查询
     */
    getListSeek() {
      this.loading = true;
      listUncheckSeek(this.queryParams).then(response => {
        // 直接使用后端返回的数据，后端已经进行了权限过滤
        this.uncheckList = response.rows.map(item => {
          const column = this.columnOptions.find(col => col.id === item.columnId);
          return {
            ...item,
            columnName: column ? column.name : '未知栏目'
          }
        });
        this.total = response.total;
        this.loading = false;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        articleId: null,
        title: null,
        articleOrigin: null,
        columnId: null,
        content: null,
        author: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        remark: null,
        coverPath: null,
        ip: null,
        pubdate: null,
        state: null,
        appval: null,
        littleTitle1: null, // 清空副标题1
        littleTitle2: null, // 清空副标题2
        attachment: null, // 清空附件
      };
      this.subtitles = []; // 清空副标题数组

      // 重置审批表状态
      this.appvalState = {
        currentUrl: null,
        pendingFile: null,
        isRemoved: false,
        originalUrl: null,
      };

      // 重置文件列表
      this.appvalFileList = [];
      this.attachmentFileList = [];
      this.fileList = []; // 清空封面文件列表
      this.uploadAppvalFile = null;
      this.uploadAttachmentFile = null;
      this.uploadFile = null; // 清空待上传的封面文件
      this.temporaryAttachmentUrl = null; // 清空临时附件URL

      this.resetForm("form");

      // 清空Element UI上传组件的内部状态
      this.$nextTick(() => {
        // 清空审批表上传组件
        if (this.$refs.appvalUpload) {
          this.$refs.appvalUpload.clearFiles();
        }
        // 清空附件上传组件
        if (this.$refs.attachmentUpload) {
          this.$refs.attachmentUpload.clearFiles();
        }
        // 清空封面上传组件（仅在媒体聚焦栏目时显示）
        if (this.$refs.upload) {
          this.$refs.upload.clearFiles();
        }
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      // 处理日期区间参数
      if (this.dateRange && this.dateRange.length === 2) {
        this.queryParams.beginPubdate = this.dateRange[0];
        this.queryParams.endPubdate = this.dateRange[1];
      } else {
        this.queryParams.beginPubdate = null;
        this.queryParams.endPubdate = null;
      }
      console.log("查询状态", this.queryParams.state);
      if (this.queryParams.state != null || this.isAdmin == true) {
        this.isSeekMode = true; // 设置为参数查询模式
        this.getListSeek();
      } else {
        this.isSeekMode = false; // 设置为默认查询模式
        this.getList();
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.dateRange = [];
      this.queryParams.content = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.articleId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push({
        path: '/uncheck/uncheck-form/index',
        query: { mode: 'add' }
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const articleId = row.articleId || this.ids;
      this.$router.push({
        path: '/uncheck/uncheck-form/index',
        query: {
          mode: 'edit',
          id: articleId
        }
      });
    },

     // 添加文章来源到历史记录 - 使用固定大小为10的循环缓冲区
    addToSourceHistory(source) {
      if (!source) return;

      // 从 localStorage 获取现有数据
      let storedHistory = [];
      const storedHistoryStr = localStorage.getItem('sourceHistory');
      if (storedHistoryStr) {
        try {
          storedHistory = JSON.parse(storedHistoryStr);
        } catch (e) {
          console.error('解析历史记录失败:', e);
          storedHistory = [];
        }
      }

      // 检查是否已存在
      const existingIndex = storedHistory.findIndex(item => item.value === source);
      if (existingIndex !== -1) {
        // 如果已存在，将其移到数组开头
        const existingItem = storedHistory.splice(existingIndex, 1)[0];
        storedHistory.unshift(existingItem);
      } else {
        // 如果不存在，添加到数组开头
        storedHistory.unshift({ value: source, timestamp: Date.now() });

        // 如果数组长度超过10，移除最后一个元素
        if (storedHistory.length > 10) {
          storedHistory.pop();
        }
      }

      // 更新 localStorage
      localStorage.setItem('sourceHistory', JSON.stringify(storedHistory));

      // 更新当前组件的 sourceHistory（只保存值）
      this.sourceHistory = storedHistory.map(item => item.value);
    },
    /** 提交按钮 */
    async submitForm() {
      // 在表单验证之前，先同步封面数据
      if (this.isMediaFocusColumn && this.fileList && this.fileList.length > 0 && !this.form.coverPath) {
        // 如果fileList中有文件但form.coverPath为空，说明用户上传了图片但还没有保存到form中
        // 这里我们设置一个临时标识，表示有封面图片
        this.form.coverPath = 'uploaded'; // 临时标识
      }

      this.$refs["form"].validate(async valid => {
        if (!valid) return;

        // 检查是否上传了审批表
        if (!this.isValidAppval()) {
          this.$modal.msgError("请上传审批表");
          return;
        }

        // 检查封面是否满足要求
        if (!this.validateCover()) {
          return;
        }

        try {
          // 检查是否有文件需要上传
          const hasFilesToUpload = this.uploadFile || this.needUploadAppval();
          let loadingInstance = null;

          if (hasFilesToUpload) {
            loadingInstance = this.$loading({
              lock: true,
              text: '上传中请等待...',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            });
          }

          // 1. 处理封面上传
          if (this.uploadFile) {
            console.log('处理封面上传');
            await this.uploadFileToServer(this.uploadFile);
          } else {
            console.log('跳过封面上传 - 没有选择封面文件');
          }


          // 2. 处理审批表上传
          await this.handleAppvalUpload();

          // 3. 处理附件上传
          // 将临时附件URL保存到表单中
          if (this.temporaryAttachmentUrl) {
            console.log('使用临时附件URL:', this.temporaryAttachmentUrl);
            this.form.attachment = this.temporaryAttachmentUrl;
          } else if (this.form.attachment === undefined) {
            // 如果没有附件且form.attachment未定义，设置为null
            this.form.attachment = null;
          }
          console.log('最终使用的附件URL:', this.form.attachment);

          // 4. 处理文章内容中的本地图片上传到OSS
          if (this.form.content) {
            console.log('处理文章内容中的本地图片上传到OSS');
            try {
              // 直接使用正则表达式替换本地图片路径
              const localImageRegex = /<img[^>]*src=["'](\/dev-api\/profile\/upload\/[^"']+)["'][^>]*>/g;
              let match;
              const processedPaths = new Set();

              // 找到所有本地图片路径并上传到OSS
              while ((match = localImageRegex.exec(this.form.content)) !== null) {
                const fullImgTag = match[0];
                const localPath = match[1];

                // 避免重复处理
                if (processedPaths.has(localPath)) {
                  continue;
                }
                processedPaths.add(localPath);

                try {
                  // 获取图片并上传到OSS
                  const response = await fetch(localPath);
                  const blob = await response.blob();
                  const fileName = localPath.split('/').pop() || `content_image_${Date.now()}.jpg`;
                  const file = new File([blob], fileName, { type: blob.type });

                  // 压缩图片
                  console.log('提交前压缩文章内容图片');
                  const compressedFile = await this.compressImage(file);

                  // 上传到OSS
                  const uploadResult = await uploadContentImage(compressedFile);
                  if (uploadResult.code === 200) {
                    // 替换HTML中的路径
                    const newImgTag = fullImgTag.replace(localPath, uploadResult.url);
                    this.form.content = this.form.content.replace(new RegExp(localPath.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g'), uploadResult.url);
                    console.log(`图片路径已替换: ${localPath} -> ${uploadResult.url}`);
                  }
                } catch (uploadError) {
                  console.error('图片上传失败:', uploadError);
                }
              }
            } catch (error) {
              console.error('处理文章内容图片失败:', error);
              this.$message.warning('文章内容中的本地图片处理失败，将保存原始内容');
            }
          }

          // 4. 不同权限修改逻辑判断
          if (this.form.articleId != null) {
            console.log("现在的用户权限:", this.canAdd);
            // 无论是市局还是分局，修改已审核的文章都变为未审核
            if (this.form.state == '1') {
              // 删除对应的已审核文章
              await delArticleByAuditId(this.form.articleId);
              // 状态变为未审核
              this.form.state = '0';
              // 清除审核日期
              this.form.clearPubdate = true;
            }
            // 修改驳回或未审核的文章，状态保持未审核
            else if (this.form.state == '2' || this.form.state == '0') {
              this.form.state = '0';
            }
          }

          // 如果是市局用户，将文章来源添加到历史记录中
          if (!this.canAdd && this.form.articleOrigin) {
            this.addToSourceHistory(this.form.articleOrigin);
          }

          // 将责任编辑添加到历史记录中
          if (this.form.author) {
            this.addToAuthorHistory(this.form.author);
          }

          const apiMethod = this.form.articleId ? updateUncheck : addUncheck;
          await apiMethod(this.form);
          // 关闭加载提示
          if (loadingInstance) {
            loadingInstance.close();
          }
          this.$modal.msgSuccess(this.form.articleId ? "修改成功" : "新增成功");
          this.open = false;
          this.getList();

        }
        catch (error) {
          console.error('操作失败:', error);
          // 如果是封面大小错误，避免重复显示提醒
          if (error.message === '封面大小不能小于1MB!') {
            // 提醒已经在uploadFileToServer中显示过了，这里不再重复显示
          } else {
            this.$message.error(`操作失败: ${error.message}`);
          }
           // 发生错误时关闭加载提示
        }finally{
           // 发生错误时关闭加载提示
          if (this.$loading) {
            // 关闭所有加载实例
            const loadingInstances = document.querySelectorAll('.el-loading-mask');
            if (loadingInstances.length > 0) {
              this.$loading().close();
            }
          }
        }
      });
    },

    /** 保存草稿 */
    async handleSaveDraft() {
      this.$refs["form"].validate(async valid => {
        if (!valid) return;

        // 检查媒体聚焦栏目是否上传了封面图片且大小是否符合要求
        if (this.isMediaFocusColumn) {
          // 检查是否有封面图片：form.coverPath、uploadFile 或 fileList 中有文件
          const hasCoverImage = this.form.coverPath ||
                               this.uploadFile ||
                               (this.fileList && this.fileList.length > 0);

          if (hasCoverImage) {
            // 检查封面图片大小是否小于1MB
            if (this.uploadFile && this.uploadFile instanceof File) {
              const isLt1M = this.uploadFile.size / 1024 / 1024 < 1;
              if (isLt1M) {
                this.$modal.msgError("媒体聚焦栏目封面图片大小不能小于1MB!");
                return;
              }
            }
          }
        }

        // 保存草稿时不需要强制验证审批表，但需要处理审批表的上传和移除逻辑
        await this.handleAppvalUploadAndValidate();

        try {
          // 检查是否有文件需要上传
          const hasFilesToUpload = this.uploadFile || this.needUploadAppval();
          let loadingInstance = null;

          if (hasFilesToUpload) {
            loadingInstance = this.$loading({
              lock: true,
              text: '上传中请等待...',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            });
          }

          // 1. 处理封面上传
          if (this.uploadFile && this.uploadFile instanceof File) {
            console.log('处理封面上传');
            const response = await this.uploadFileToServer(this.uploadFile);
            // 确保封面路径被正确设置到表单中
            if (response && response.code === 200 && response.url) {
              this.form.coverPath = response.url;
              console.log('封面路径已设置到表单中:', this.form.coverPath);
            }
          } else if (this.uploadFile === null && this.fileList.length === 0 && this.form.coverPath) {
            // 用户明确移除了封面图片
            console.log('用户移除了封面图片');
            this.form.coverPath = null;
          } else if (this.uploadFile === null && this.fileList.length === 0 && !this.form.coverPath) {
            // 用户没有上传封面图片，保持原状
            console.log('保持原有封面状态');
          } else {
            console.log('跳过封面上传 - 没有选择封面文件');
          }

          // 2. 审批表已通过handleAppvalUploadAndValidate处理，无需再次上传
          console.log('审批表已通过独立流程处理，跳过重复上传');

          // 3. 处理附件上传
          // 将临时附件URL保存到表单中
          if (this.temporaryAttachmentUrl) {
            console.log('使用临时附件URL:', this.temporaryAttachmentUrl);
            this.form.attachment = this.temporaryAttachmentUrl;
          } else if (this.form.attachment === undefined) {
            // 如果没有附件且form.attachment未定义，设置为null
            this.form.attachment = null;
          }
          console.log('最终使用的附件URL:', this.form.attachment);

          // 4. 处理文章内容中的本地图片上传到OSS
          if (this.form.content) {
            console.log('处理文章内容中的本地图片上传到OSS');
            try {
              // 直接使用正则表达式替换本地图片路径
              const localImageRegex = /<img[^>]*src=["'](\/dev-api\/profile\/upload\/[^"']+)["'][^>]*>/g;
              let match;
              const processedPaths = new Set();

              // 找到所有本地图片路径并上传到OSS
              while ((match = localImageRegex.exec(this.form.content)) !== null) {
                const fullImgTag = match[0];
                const localPath = match[1];

                // 避免重复处理
                if (processedPaths.has(localPath)) {
                  continue;
                }
                processedPaths.add(localPath);

                try {
                  // 获取图片并上传到OSS
                  const response = await fetch(localPath);
                  const blob = await response.blob();
                  const fileName = localPath.split('/').pop() || `content_image_${Date.now()}.jpg`;
                  const file = new File([blob], fileName, { type: blob.type });

                  // 压缩图片
                  console.log('提交前压缩文章内容图片');
                  const compressedFile = await this.compressImage(file);

                  // 上传到OSS
                  const uploadResult = await uploadContentImage(compressedFile);
                  if (uploadResult.code === 200) {
                    // 替换HTML中的路径
                    const newImgTag = fullImgTag.replace(localPath, uploadResult.url);
                    this.form.content = this.form.content.replace(new RegExp(localPath.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g'), uploadResult.url);
                    console.log(`图片路径已替换: ${localPath} -> ${uploadResult.url}`);
                  }
                } catch (uploadError) {
                  console.error('图片上传失败:', uploadError);
                }
              }
            } catch (error) {
              console.error('处理文章内容图片失败:', error);
              this.$message.warning('文章内容中的本地图片处理失败，将保存原始内容');
            }
          }

          // 4. 保存草稿逻辑前的最终审批表状态检查
          console.log('保存草稿前最终审批表状态检查:', {
            formAppval: this.form.appval,
            currentUrl: this.appvalState.currentUrl,
            originalUrl: this.appvalState.originalUrl,
            isRemoved: this.appvalState.isRemoved
          });

          // 确保审批表状态正确同步
          if (this.appvalState.currentUrl && !this.form.appval) {
            this.form.appval = this.appvalState.currentUrl;
            console.log('强制同步审批表状态到form.appval');
          }

          // 创建草稿数据
          const draftData = { ...this.form };
          draftData.status = 0; // 草稿状态

          // 如果是从已发布的文章编辑并保存到草稿箱
          if (this.form.articleId && this.title === "修改文章") {
            try {
              if (this.form.state === '1') {
                try {
                  // 删除已审核的文章（先检查是否存在）
                  await delArticleByAuditId(this.form.articleId);
                  console.log('修改已审核的文章已删除');
                } catch (deleteError) {
                  // 如果删除失败（可能因为文章不存在），记录日志但不中断操作，不显示错误提醒
                  console.warn('删除已审核文章时出错（文章可能不存在）:', deleteError.message);
                  // 不显示错误提醒给用户
                }
              }

              // 删除uncheck已有的文章（从uncheck表中删除）
              try {
                await delUncheck(this.form.articleId);
              } catch (deleteError) {
                // 如果删除失败，记录日志但不中断操作，不显示错误提醒
                console.warn('删除uncheck文章时出错:', deleteError.message);
                // 不显示错误提醒给用户
              }

              // 保存到草稿箱
              await addUncheckDraft(draftData);
            } catch (error) {
              console.error("保存草稿失败:", error);
              // 不向用户显示错误，只记录日志
              console.warn("保存草稿失败（不向用户显示）:", error.message);
              // 不重新抛出错误，避免向用户显示错误提示
              return;
            }
          } else {
            if (!draftData.title || !draftData.columnId || !draftData.content) {
              this.$message.error("标题、栏目名称或内容不能为空");
              return;
            }

            try {
              if (this.form.articleId) {
                await updateUncheckDraft(draftData);
              } else {
                await addUncheckDraft(draftData);
              }
            } catch (draftError) {
              console.error("草稿保存失败:", draftError);
              this.$message.error(`草稿保存失败: ${draftError.message}`);
              throw draftError; // 重新抛出错误以便上层捕获
            }
          }

          // 关闭加载提示
          if (loadingInstance) {
            loadingInstance.close();
          }

          this.$modal.msgSuccess("草稿保存成功");
          this.open = false;
          this.loadDraftList(); // 重新加载草稿列表
          this.getList(); // 重新加载主列表
          // 保存草稿后打开草稿箱列表
          this.draftBoxVisible = true;

        } catch (error) {
          console.error('保存草稿失败:', error);
          // 不向用户显示错误，只记录日志
          console.warn("保存草稿失败（不向用户显示）:", error.message);
          // 对于特定的审批表相关错误，提供更友好的提示
          // if (error.message && error.message.includes('appval')) {
          //   this.$message.error(`保存草稿失败: 审批表处理异常，请重新上传审批表`);
          // } else {
          //   this.$message.error(`保存草稿失败: ${error.message}`);
          // }
        } finally {
          // 发生错误时关闭加载提示
          if (this.$loading) {
            // 关闭所有加载实例
            const loadingInstances = document.querySelectorAll('.el-loading-mask');
            if (loadingInstances.length > 0) {
              this.$loading().close();
            }
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const articleIds = row.articleId || this.ids;
      this.$modal.confirm('是否确认删除uncheck编号为"' + articleIds + '"的数据项？').then(function () {
        return delUncheck(articleIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
        // 删除失败时不向用户显示错误提示，只记录日志
        console.warn("删除uncheck文章失败，但不向用户显示错误提示");
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('uncheck/uncheck/export', {
        ...this.queryParams
      }, `uncheck_${new Date().getTime()}.xlsx`)
    },

    /** 打开草稿箱 */
    handleOpenDraftBox() {
      this.draftBoxVisible = true;
      this.loadDraftList();
    },

    /** 加载草稿列表 */
    loadDraftList() {
      this.draftLoading = true;
      listUncheckDraft(this.queryParams).then(response => {
        this.draftList = response.rows || [];
        // 处理栏目名称映射
        this.draftList = this.draftList.map(item => {
          const column = this.columnOptions.find(col => col.id === item.columnId);
          return {
            ...item,
            columnName: column ? column.name : '未知栏目'
          };
        }).sort((a, b) => b.articleId - a.articleId); // 按articleId降序排列
        this.draftLoading = false;
      }).catch(error => {
        console.error("加载草稿列表失败:", error);
        this.draftLoading = false;
        this.$message.error("加载草稿列表失败");
      });
    },

    /** 编辑草稿 */
    handleEditDraft(row) {
      this.reset();
      getUncheckDraft(row.articleId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改草稿";

        // 初始化审批表状态
        // 初始化封面文件列表
        if (this.form.coverPath) {
          this.fileList = [{
            name: "封面图片",
            url: this.form.coverPath
          }];
          this.uploadFile = null;
          console.log("初始化封面文件列表");
          // 确保在下一次DOM更新后刷新上传组件
          this.$nextTick(() => {
            if (this.$refs.upload) {
              this.$refs.upload.fileList = this.fileList;
            }
          });
        } else {
          this.fileList = [];
          this.uploadFile = null;
          console.log("清空封面文件列表");
          // 确保在下一次DOM更新后刷新上传组件
          this.$nextTick(() => {
            if (this.$refs.upload) {
              this.$refs.upload.fileList = this.fileList;
            }
          });
        }

        if (this.form.appval) {
          this.appvalState.currentUrl = this.form.appval;
          this.appvalState.originalUrl = this.form.appval;
          this.appvalFileList = [{
            name: '审批表',
            url: this.form.appval
          }];
        } else {
          this.appvalState.currentUrl = null;
          this.appvalState.originalUrl = null;
          this.appvalFileList = [];
        }
        // 确保uploadAppvalFile初始化为null，避免使用之前缓存的数据
        this.uploadAppvalFile = null;
        // 重置其他审批表状态
        this.appvalState.pendingFile = null;
        this.appvalState.isRemoved = false;

        // 初始化附件文件列表
        if (this.form.attachment) {
          this.attachmentFileList = [{
            name: this.getAttachmentFileName(this.form.attachment),
            url: this.form.attachment
          }];
          this.uploadAttachmentFile = null;
          console.log("初始化附件文件列表");
        } else {
          this.attachmentFileList = [];
          this.uploadAttachmentFile = null;
          console.log("清空附件文件列表");
        }

        // 同步副标题状态
        this.subtitles = [];
        if (this.form.littleTitle1) {
          this.subtitles.push('littleTitle1');
        }
        if (this.form.littleTitle2) {
          this.subtitles.push('littleTitle2');
        }
      });
    },

    /** 更新草稿 */
    async handleUpdateDraft() {
      // 在表单验证之前，先同步封面数据
      if (this.isMediaFocusColumn && this.fileList && this.fileList.length > 0 && !this.form.coverPath) {
        this.form.coverPath = 'uploaded'; // 临时标识
      }

      this.$refs["form"].validate(async valid => {
        if (!valid) return;

        this.draftLoading = true;

        // 检查媒体聚焦栏目是否上传了封面图片且大小是否符合要求
        if (this.isMediaFocusColumn) {
          // 检查是否有封面图片：form.coverPath、uploadFile 或 fileList 中有文件
          const hasCoverImage = this.form.coverPath ||
                               this.uploadFile ||
                               (this.fileList && this.fileList.length > 0);

          if (hasCoverImage) {
            // 检查封面图片大小是否小于1MB
            if (this.uploadFile && this.uploadFile instanceof File) {
              const isLt1M = this.uploadFile.size / 1024 / 1024 < 1;
              if (isLt1M) {
                this.$modal.msgError("媒体聚焦栏目封面图片大小不能小于1MB!");
                return;
              }
            }
          }
        }

        try {
          // 检查是否有文件需要上传
          const hasFilesToUpload = this.uploadFile || this.needUploadAppval();
          let loadingInstance = null;

          if (hasFilesToUpload) {
            loadingInstance = this.$loading({
              lock: true,
              text: '上传中请等待...',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            });
          }

          // 1. 处理封面上传
          if (this.uploadFile && this.uploadFile instanceof File) {
            console.log('处理封面上传');
            const response = await this.uploadFileToServer(this.uploadFile);
            // 确保封面路径被正确设置到表单中
            if (response && response.code === 200 && response.url) {
              this.form.coverPath = response.url;
              console.log('封面路径已设置到表单中:', this.form.coverPath);
            }
          } else if (this.uploadFile === null && this.fileList.length === 0 && this.form.coverPath) {
            // 用户明确移除了封面图片
            console.log('用户移除了封面图片');
            this.form.coverPath = null;
          } else if (this.uploadFile === null && this.fileList.length === 0 && !this.form.coverPath) {
            // 用户没有上传封面图片，保持原状
            console.log('保持原有封面状态');
          } else {
            console.log('跳过封面上传 - 没有选择封面文件');
          }

          // 2. 处理审批表上传，但不强制验证
          await this.handleAppvalUploadAndValidate();

          // 3. 处理附件上传
          // 将临时附件URL保存到表单中
          if (this.temporaryAttachmentUrl) {
            console.log('使用临时附件URL:', this.temporaryAttachmentUrl);
            this.form.attachment = this.temporaryAttachmentUrl;
          } else if (this.form.attachment === undefined) {
            // 如果没有附件且form.attachment未定义，设置为null
            this.form.attachment = null;
          }
          console.log('最终使用的附件URL:', this.form.attachment);

          // 4. 处理文章内容中的本地图片上传到OSS
          if (this.form.content) {
            console.log('处理文章内容中的本地图片上传到OSS');
            try {
              // 直接使用正则表达式替换本地图片路径
              const localImageRegex = /<img[^>]*src=["'](\/dev-api\/profile\/upload\/[^"']+)["'][^>]*>/g;
              let match;
              const processedPaths = new Set();

              // 找到所有本地图片路径并上传到OSS
              while ((match = localImageRegex.exec(this.form.content)) !== null) {
                const fullImgTag = match[0];
                const localPath = match[1];

                // 避免重复处理
                if (processedPaths.has(localPath)) {
                  continue;
                }
                processedPaths.add(localPath);

                try {
                  // 获取图片并上传到OSS
                  const response = await fetch(localPath);
                  const blob = await response.blob();
                  const fileName = localPath.split('/').pop() || `content_image_${Date.now()}.jpg`;
                  const file = new File([blob], fileName, { type: blob.type });

                  // 压缩图片
                  console.log('提交前压缩文章内容图片');
                  const compressedFile = await this.compressImage(file);

                  // 上传到OSS
                  const uploadResult = await uploadContentImage(compressedFile);
                  if (uploadResult.code === 200) {
                    // 替换HTML中的路径
                    const newImgTag = fullImgTag.replace(localPath, uploadResult.url);
                    this.form.content = this.form.content.replace(new RegExp(localPath.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g'), uploadResult.url);
                    console.log(`图片路径已替换: ${localPath} -> ${uploadResult.url}`);
                  }
                } catch (uploadError) {
                  console.error('图片上传失败:', uploadError);
                }
              }
            } catch (error) {
              console.error('处理文章内容图片失败:', error);
              this.$message.warning('文章内容中的本地图片处理失败，将保存原始内容');
            }
          }

          // 4. 更新草稿逻辑
          const draftData = { ...this.form };
          draftData.status = 0; // 草稿状态

          if (this.form.articleId) {
            // 更新草稿
            await updateUncheckDraft(draftData);
          } else {
            // 新增草稿
            await addUncheckDraft(draftData);
          }

          // 关闭加载提示
          if (loadingInstance) {
            loadingInstance.close();
          }

          this.$modal.msgSuccess("草稿更新成功");
          this.open = false;
          this.loadDraftList(); // 重新加载草稿列表
          // 更新草稿后不关闭草稿箱列表弹窗

        }catch (error) {
          console.error('更新草稿失败:', error);
          this.$message.error(`更新草稿失败: ${error.message}`);
        } finally {
          this.draftLoading = false;
          // 发生错误时关闭加载提示
          if (this.$loading) {
            // 关闭所有加载实例
            const loadingInstances = document.querySelectorAll('.el-loading-mask');
            if (loadingInstances.length > 0) {
              this.$loading().close();
            }
          }
        }
      });
    },

    /** 发布草稿 */
    handlePublishDraft(row) {
      // 检查是否上传了审批表
      if (!row.appval || row.appval === '') {
        this.$modal.msgError("请上传审批表后再发布");
        return;
      }

      // 检查媒体聚焦栏目是否上传了封面图片
      // 获取栏目信息来判断是否为媒体聚焦栏目
      const column = this.columnOptions.find(col => col.id === row.columnId);
      const isMediaFocusColumn = column && column.name === '媒体聚焦';

      if (isMediaFocusColumn && (!row.coverPath || row.coverPath === '')) {
        this.$modal.msgError("媒体聚焦栏目必须上传封面图片");
        return;
      }

      this.$modal.confirm('是否确认发布草稿"' + row.title + '"?').then(() => {
        return publishUncheckDraft(row.articleId);
      }).then(response => {
        if (response.code === 200) {
          this.$modal.msgSuccess("发布成功");
          this.loadDraftList(); // 重新加载草稿列表
          this.getList(); // 重新加载主列表
          // 发布成功后关闭草稿箱列表弹窗
          this.draftBoxVisible = false;
        } else {
          this.$modal.msgError(response.msg || "发布失败");
        }
      }).catch(() => {
        this.$modal.msgError("发布失败");
      });
    },

    /** 删除草稿 */
    handleDeleteDraft(row) {
      this.$modal.confirm('是否确认删除草稿"' + row.title + '"?').then(() => {
        return delUncheckDraft(row.articleId);
      }).then(() => {
        this.$modal.msgSuccess("删除成功");
        this.loadDraftList(); // 重新加载草稿列表
      }).catch(() => {
        this.$modal.msgError("删除失败");
      });
    },
    // 格式化日期时间
    formatDateTime(datetime) {
      if (!datetime) return '';
      // 如果是字符串格式的时间
      if (typeof datetime === 'string') {
        // 处理ISO 8601格式的时间字符串
        if (datetime.includes('T')) {
          const date = new Date(datetime);
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, '0');
          const day = String(date.getDate()).padStart(2, '0');
          const hours = String(date.getHours()).padStart(2, '0');
          const minutes = String(date.getMinutes()).padStart(2, '0');
          const seconds = String(date.getSeconds()).padStart(2, '0');
          return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }
        return datetime;
      }
      // 如果是Date对象，格式化为YYYY-MM-DD HH:mm:ss
      const year = datetime.getFullYear();
      const month = String(datetime.getMonth() + 1).padStart(2, '0');
      const day = String(datetime.getDate()).padStart(2, '0');
      const hours = String(datetime.getHours()).padStart(2, '0');
      const minutes = String(datetime.getMinutes()).padStart(2, '0');
      const seconds = String(datetime.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },


    /** 从草稿直接发布 */
    async handlePublishFromDraft() {
      this.publishLoading = true;
      try {
        // 在验证之前，先同步封面数据
        if (this.isMediaFocusColumn && this.fileList && this.fileList.length > 0 && !this.form.coverPath) {
          this.form.coverPath = 'uploaded'; // 临时标识
        }

        // 检查封面是否满足要求 - 发布时强制验证，不管是否为草稿
        // 特别检查媒体聚焦栏目是否上传了封面图片
        if (this.isMediaFocusColumn) {
          // 检查是否有封面图片：form.coverPath、uploadFile 或 fileList 中有文件
          const hasCoverImage = this.form.coverPath ||
                               this.uploadFile ||
                               (this.fileList && this.fileList.length > 0);

          console.log('发布草稿时封面验证调试信息:', {
            isMediaFocusColumn: this.isMediaFocusColumn,
            formCoverPath: this.form.coverPath,
            uploadFile: this.uploadFile,
            fileList: this.fileList,
            hasCoverImage: hasCoverImage
          });

          if (!hasCoverImage) {
            this.$modal.msgError("媒体聚焦栏目必须上传封面图片");
            return;
          }

          // 检查封面图片大小是否小于1MB
          if (this.uploadFile && this.uploadFile instanceof File) {
            const isLt1M = this.uploadFile.size / 1024 / 1024 < 1;
            if (isLt1M) {
              this.$modal.msgError("媒体聚焦栏目封面图片大小不能小于1MB!");
              return;
            }
          }
        }

        // 检查是否上传了审批表
        if (!this.isValidAppval()) {
          this.$modal.msgError("请上传审批表");
          return;
        }

        // 显示加载提示
        const loadingInstance = this.$loading({
          lock: true,
          text: '发布中，请稍候...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)',
        });

        try{
          console.log('开始从草稿直接发布，当前审批表状态:', {
            formAppval: this.form.appval,
            currentUrl: this.appvalState.currentUrl,
            originalUrl: this.appvalState.originalUrl,
            uploadAppvalFile: this.uploadAppvalFile,
            isRemoved: this.appvalState.isRemoved
          });

          // 使用独立的审批表上传和验证流程
          const isAppvalValid = await this.handleAppvalUploadAndValidate();

          console.log('审批表上传和验证完成，结果:', isAppvalValid);
          console.log('验证后审批表状态:', {
            formAppval: this.form.appval,
            currentUrl: this.appvalState.currentUrl,
            originalUrl: this.appvalState.originalUrl,
            isRemoved: this.appvalState.isRemoved
          });

          // 处理附件上传
          // 将临时附件URL保存到表单中
          if (this.temporaryAttachmentUrl) {
            console.log('使用临时附件URL:', this.temporaryAttachmentUrl);
            this.form.attachment = this.temporaryAttachmentUrl;
            console.log('附件URL设置成功:', this.temporaryAttachmentUrl);
          } else if (this.form.attachment === undefined) {
            // 如果没有附件且form.attachment未定义，设置为null
            this.form.attachment = null;
          }
          console.log('最终使用的附件URL:', this.form.attachment);

          if (!isAppvalValid) {
            this.$modal.msgError("请上传审批表");
            return;
          }

          console.log('审批表验证通过，准备发布草稿');

          // 再次确认审批表状态，确保使用最新的审批表
          console.log('发布前再次确认审批表状态:', {
            formAppval: this.form.appval,
            currentUrl: this.appvalState.currentUrl,
            originalUrl: this.appvalState.originalUrl,
            isRemoved: this.appvalState.isRemoved
          });

          // 确保form.appval是最新的
          if (this.appvalState.currentUrl) {
            this.form.appval = this.appvalState.currentUrl;
          } else if (this.appvalState.originalUrl && !this.appvalState.isRemoved) {
            this.form.appval = this.appvalState.originalUrl;
          } else if (this.appvalState.isRemoved) {
            this.form.appval = null;
          }

          console.log('最终使用的审批表URL:', this.form.appval);

          // 先更新草稿记录，确保审批表URL和附件URL被正确保存到数据库
          console.log('更新草稿记录，确保审批表URL和附件URL被保存到数据库');
          try {
            // 创建更新数据副本
            const updateData = { ...this.form };

            // 确保附件URL被正确设置
            if (this.temporaryAttachmentUrl) {
              updateData.attachment = this.temporaryAttachmentUrl;
              console.log('使用临时附件URL更新草稿:', this.temporaryAttachmentUrl);
            } else if (updateData.attachment === undefined) {
              updateData.attachment = null;
            }

            // 确保封面URL被正确设置
            console.log('更新草稿记录时的封面URL状态:', {
              formCoverPath: this.form.coverPath,
              uploadFile: this.uploadFile,
              fileList: this.fileList
            });

            // 处理封面上传
            if (this.uploadFile && this.uploadFile instanceof File) {
              console.log('检测到新的封面文件，开始上传');
              const response = await this.uploadFileToServer(this.uploadFile);
              if (response && response.code === 200 && response.url) {
                updateData.coverPath = response.url;
                this.form.coverPath = response.url;
                console.log('封面上传成功，URL已设置:', response.url);
              }
            } else if (this.uploadFile === null && this.fileList.length === 0 && this.form.coverPath) {
              // 用户明确移除了封面图片
              console.log('用户移除了封面图片');
              updateData.coverPath = null;
              this.form.coverPath = null;
            } else if (this.form.coverPath) {
              // 保持现有的封面URL
              updateData.coverPath = this.form.coverPath;
              console.log('保持现有的封面URL:', this.form.coverPath);
            }

            console.log('准备更新草稿记录，updateData内容:', updateData);
            console.log('updateData中attachment的值:', updateData.attachment);
            console.log('updateData中coverPath的值:', updateData.coverPath);

            // 调用更新草稿接口
            const updateResponse = await updateUncheckDraft(updateData);
            if (updateResponse && updateResponse.code === 200) {
              console.log('草稿记录更新成功');
            } else {
              console.warn('草稿记录更新可能失败:', updateResponse);
            }
          } catch (updateError) {
            console.error('更新草稿记录时出错:', updateError);
            // 即使更新失败也继续发布流程
          }

          // 处理文章内容中的本地图片上传到OSS
          if (this.form.content) {
            console.log("处理文章内容中的本地图片上传到OSS");
            try {
              // 直接使用正则表达式替换本地图片路径
              const localImageRegex = /<img[^>]*src=["'](\/dev-api\/profile\/upload\/[^"']+)["'][^>]*>/g;
              let match;
              const processedPaths = new Set();

              // 找到所有本地图片路径并上传到OSS
              while ((match = localImageRegex.exec(this.form.content)) !== null) {
                const fullImgTag = match[0];
                const localPath = match[1];

                // 避免重复处理
                if (processedPaths.has(localPath)) {
                  continue;
                }
                processedPaths.add(localPath);

                try {
                  // 获取图片并上传到OSS
                  const response = await fetch(localPath);
                  const blob = await response.blob();
                  const fileName = localPath.split("/").pop() || `content_image_${Date.now()}.jpg`;
                  const file = new File([blob], fileName, { type: blob.type });

                  // 压缩图片
                  console.log("提交前压缩文章内容图片");
                  const compressedFile = await this.compressImage(file);

                  // 上传到OSS
                  const uploadResult = await uploadContentImage(compressedFile);
                  if (uploadResult.code === 200) {
                    // 替换HTML中的路径
                    const newImgTag = fullImgTag.replace(localPath, uploadResult.url);
                    this.form.content = this.form.content.replace(new RegExp(localPath.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g"), uploadResult.url);
                    console.log(`图片路径已替换: ${localPath} -> ${uploadResult.url}`);
                  }
                } catch (uploadError) {
                  console.error("图片上传失败:", uploadError);
                }
              }
            } catch (error) {
              console.error("处理文章内容图片失败:", error);
              this.$message.warning("文章内容中的本地图片处理失败，将保存原始内容");
            }
          }

          // 发布草稿
          const response = await publishUncheckDraft(this.form.articleId);
          if (response && response.code === 200) {
            this.$modal.msgSuccess("发布成功");
            this.open = false;
            this.loadDraftList();
            this.getList(); // 刷新文章列表
            // 发布成功后关闭草稿箱列表弹窗
            this.draftBoxVisible = false;
          } else {
            throw new Error(response.msg || "发布失败");
          }
        } finally {
          // 关闭加载提示
          loadingInstance.close();
        }

      }catch (error) {
        console.error("发布草稿失败:", error);
        this.$message.error(`发布草稿失败: ${error.message}`);
      } finally {
        this.publishLoading = false;
      }
    }
  }
}
</script>

<style scoped>
.content-cell {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.5;
  max-height: 3em;
  word-break: break-all; /* 确保长单词也能换行 */
}
</style>

<style scoped>

.content-cell {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  line-clamp: 2; /* 标准写法 */
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.5;
  max-height: 3em;
  word-break: break-all;
}

.audit-content {
  max-height: 400px;
  overflow-y: auto;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

/* 审核弹窗字段内容样式 */
.audit-field-content {
  padding: 8px 12px;
  background-color: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  min-height: 32px;
  line-height: 1.5;
  word-break: break-all;
}

/* 审核弹窗图片容器样式 */
.audit-image-container {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  min-height: 100px;
  max-width: 100%;
}

.audit-preview-image {
  max-width: 100%;
  max-height: 200px;
  object-fit: contain;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

/* 自定义弹窗样式 */
.audit-dialog {
  display: flex;
  flex-direction: column;
  max-height: 90vh;
}

.audit-dialog .el-dialog__body {
  flex: 1;
  overflow-y: auto;
  max-height: calc(90vh - 120px);
}

/* 图片容器样式 */
.image-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100px;
  min-width: 100px;
}

.preview-image {
  max-width: 100%;
  max-height: 200px;
  object-fit: contain;
  border-radius: 4px;
}

.table-image-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 50px;
  width: 50px;
  overflow: hidden;
}

.table-preview-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: cover;
  border-radius: 2px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .audit-dialog {
    width: 95% !important;
  }
}

@media (max-height: 768px) {
  .audit-dialog .el-dialog__body {
    max-height: calc(85vh - 120px);
  }
}

.subtitle-item {
  margin-bottom: 20px;
}

/* 草稿箱弹窗样式 */
.draft-dialog {
  display: flex;
  flex-direction: column;
  max-height: 90vh;
}

.draft-dialog .el-dialog__body {
  flex: 1;
  overflow-y: auto;
  max-height: calc(90vh - 120px);
}

@media (max-width: 1200px) {
  .draft-dialog {
    width: 95% !important;
  }
}

@media (max-height: 768px) {
  .draft-dialog .el-dialog__body {
    max-height: calc(85vh - 120px);
  }
}

.has-approval {
  color: #67c23a;
  font-weight: bold;
}

.no-approval {
  color: #f56c6c;
  font-weight: bold;
}

/* 草稿相关按钮样式 */
.draft-publish-button {
  font-weight: bold;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.draft-publish-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.draft-save-button {
  font-weight: bold;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.draft-save-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

</style>

